<?php

class HotSquareController
{
    private $hotSquareModel;
    private $autoUidModel;
    private $diaryAttachmentModel;
    private static $modelPool;
	private $diaryListCacheModel;
	private $feedModel;
	private $diaryListModel;

    function __construct()
    {
        $this->diaryAttachmentModel =   new DiaryAttachmentModel();
        $this->hotSquareModel       =   new HotSquareModel();
        $this->autoUidModel         =   new AutoUidModel();
		$this->feedModel            =   new FeedModel();
		$this->diaryListModel       =   new DiaryListModel();
		$this->diaryListCacheModel  =   new DiaryListCacheModel();
    }

    public function postSquare($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['type']))
        {
            AC::$errorNo    =   'HSCC001';
            return  FALSE;
        }
        # check self nickname & send info to square   /*{{{*/
        $userBaseInfo   =   $this->autoUidModel->getUserInfo($info['uid']);
        if (!isset($userBaseInfo['nickname']))
        {
            AC::$errorNo    =   'HSCC002';
            return  FALSE;
        }
        $info['eUid']       =   $userBaseInfo['uid'];
        $info['eNickname']  =   $userBaseInfo['nickname'];
        # & send info to square!
        $sendResult =   $this->hotSquareModel->setSquareInfo($info);
        if (empty($sendResult))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }/*}}}*/
    
        return  TRUE;
    }/*}}}*/
    
    /**
     * 分类信息
     * 情感    健康    星座    摄影    搞笑    美妆
     *     
     * @param  $info
     */
    public function getSquareCategory($info)/*{{{*/
    {
        $url = AC::getProtocolUriByOS(AC::$cdn_url_img);
		$result = array();
		$result[] = array("cid"=>"1", "name"=>"情感", "img"=>"{$url}/7B/27/47/Image/2DED2B83-84B0-2125-0B10-5241553EB4CA.jpg", "type"=>"1");
		$result[] = array("cid"=>"10", "name"=>"搞笑", "img"=>"{$url}/7B/27/47/Image/7E717451-A340-49AD-437A-52415557E858.jpg", "type"=>"1");
		$result[] = array("cid"=>"7", "name"=>"星座", "img"=>"{$url}/7B/27/47/Image/9EE342EA-891D-31CD-0691-524155020240.jpg", "type"=>"1");
		$result[] = array("cid"=>"9", "name"=>"美图", "img"=>"{$url}/7B/27/47/Image/CDA75F04-C116-9FE4-687A-5241566BEE93.jpg", "type"=>"1");
		$result[] = array("cid"=>"6", "name"=>"美妆", "img"=>"{$url}/7B/27/47/Image/42D3A325-9CDC-A4AF-FA87-524156CF61A7.jpg", "type"=>"1");
		$result[] = array("cid"=>"5", "name"=>"健康", "img"=>"{$url}/7B/27/47/Image/59EF3F33-33E3-0967-4949-524156FF2BD8.jpg", "type"=>"1");
		
    	return  $result;
    }/*}}}*/

    /**
     * 广场最新,新接口,下拉时不用传id
     * @param unknown $info
     * @return NULL|multitype:multitype:string NULL unknown Ambigous <multitype:multitype: string NULL unknown Ambigous <string, unknown> Ambigous <NULL, boolean, unknown> , multitype:multitype: NULL Ambigous <boolean, unknown, multitype:> >
     */
    public function getSquareList($info)/*{{{*/
    {
        // 兼容老版本下啦刷新时传了id的字段影响分页
        if (isset($info['listMode']) && empty($info['listMode'])){
            unset($info['id']);
        }
	    $squareList = $this->diaryListCacheModel->getSquareNewList( $info );
        if (empty($squareList)  ||  !is_array($squareList)) return  NULL;
    
        $result =   array();
        foreach ($squareList    as  &$squareDetail)
        {
            $tmp = $this->diaryListModel->getDiaryInfoByBodyId($squareDetail['bodyId']);
            if(empty($tmp)){
                continue;
            }
            $tmp['id']    =   $tmp['bodyId'];
            $squareDetail =   $this->feedModel->square($tmp);
            $result[]     =   $squareDetail;
        }

        // 更新用户活跃时间
        $this->autoUidModel->updateUserLastActivity(AC::HOST_UID);
        return $result;
    }/*}}}*/
    
    // 搜索出来的日记已被删除的时候组装空结构
    private function squareData($diaryInfo){
        $detail = array();
        $detail['id']                =     strval($diaryInfo['id']);
        $detail['uid']               =     strval($diaryInfo['eUid']);
        $detail['rUid']              =     '0' ;
        $detail['rBodyId']           =     '0' ;
        $detail['bodyId']            =     strval($diaryInfo['bodyId']);
        $detail['title']             =     '' ;
        $detail['abbreviation']      =     $diaryInfo['content'];
        $detail['secret']            =     '0' ;
        $detail['attachmentPath']    =     '';
        $detail['attachmentList']    =     array();
        $detail['time']              =     strval($diaryInfo['time']);
        $detail['status']            =     '0' ;
        $detail['label']             =     strval($diaryInfo['label']);
        $detail['commentPeople']     =     '0' ;
        $detail['repostTimes']       =     '0' ;
        $detail['viewTimes']         =     '0' ;
        $detail['commentTimes']      =     '0' ;
        $detail['likeTimes']         =     '0' ;
        $detail['shareTimes']        =     '0' ;
        
        return $detail;
    }
    
    public function getSquareLatestUserList($info)/*{{{*/
    {
        $result =$this->hotSquareModel->getSquareLatestUserList($info);
        foreach($result as &$value){
            if (empty($value['uid'])){
                continue;
            }
            $userInfo           =    $this->autoUidModel->getUserInfo($value['uid']);
            $value['avatar']    =    $userInfo['avatar'];
        }
        return $result;
    }/*}}}*/

    public function removeSquare($info)/*{{{*/
    {
        return  $this->hotSquareModel->removeSquare($info);
    }/*}}}*/

    public function getDiaryInfoUseLike($diaryInfo)/*{{{*/
    {
        $result =   $this->hotSquareModel->getDiaryInfoUseLike($diaryInfo);
        if (empty($result)  ||  !is_array($result)) return  NULL;

        $searchResult   =   array();
        foreach ($result    as  $diaryDetail)
        {
            #   $diaryDetail['detail']  =   $this->getSquareDetail($diaryDetail);
            $detail =   $this->getSquareDetail($diaryDetail);
            if (empty($detail)) continue;
            $diaryDetail['retweeted_status']  = $this->diaryListModel->manipulationListData($detail);
            $diaryDetail['detail']  =   $detail;
            $searchResult[] =   $diaryDetail;
        }

        return  $searchResult;
    }/*}}}*/
    
    public function getSearchDiary($diaryInfo)/*{{{*/
    {
        if (isset($diaryInfo['id'])){
            $result =   $this->hotSquareModel->oldSearchDiaryInfo($diaryInfo);
        }
        if (isset($diaryInfo['start'])){
            $result =   $this->hotSquareModel->getSearchDiaryInfo($diaryInfo);
        }
        
        if (empty($result)  ||  !is_array($result)) return  NULL;
    
        $searchResult   =   array();
        foreach ($result    as  $diaryDetail)
        {
            $tmp = $this->diaryListModel->getDiaryInfoByBodyId($diaryDetail['bodyId']);
    
            if(empty($tmp)){
                continue;
            }
            $tmp['id']    =    $diaryDetail['id'];
            $squareDetail =   $this->feedModel->square($tmp);
            $searchResult[]     =   $squareDetail;
        }
        
        return  $searchResult;
    }/*}}}*/
    
    # 添加推荐的用户
    public function addRecommentUser($info)/*{{{*/
    {
    	if (!isset($info['type']) || empty($info['type']))
    	{
    		$info['type'] = 0;
    	}
    	 
    	$type			=	intval($info['type']);
    	$info['uid']	=	trim($info['uid']);
    	$uids	  		=   explode(',',$info['uid']);
    	$times	 		=	array();
    	for ($i=0;$i<count($uids);$i++)
    	{
    		$userinfo = $this->autoUidModel->getUserInfo($uids[$i]);
    		if ($userinfo['uid'])
    		{
    			$times[]	=	$this->getLastestDiary($uids[$i]);
    		}
    	}
    	 
    	$arr = array_combine($uids, $times);
    	foreach ($arr as $key=>$values)
    	{
    		$score		=	$this->diaryListCacheModel->getUserScore(strval($key));
    		if($score != 1)
	    	{
	    		$result =   $this->diaryListCacheModel->addRecommentUser($type, intval($values), strval($key));
	    	}
    	}
    	return $result;
    }/*}}}*/
    
    # 推荐用户列表
    public function recommentUserList($info)/*{{{*/
    {
    	if (empty($info['uid'])) {
    		AC::$errorNo    =   'FOC001';
    		return  FALSE;
    	}
    	
    	$uid = AC::HOST_UID;
    	// 查询用户标签情况，根据标签搜索用户
    	$userInfo = $this->autoUidModel->getUserInfo($uid);
    	if (!empty($userInfo['tag_list']) && AC::$recommentByTagVersion){
    	    $tags = array();
    	    foreach ($userInfo['tag_list'] as $value){
    	        $tags[] = $value['name'];
    	    }
    	    $tags_str = implode(',', $tags);
    	    
    	    $data = array('start' => intval($info['start']), 'length' => intval($info['length']), 'tags_str' => $tags_str);
    	    $uids = $this->hotSquareModel->getSearchUsersByTag($uid, $data);
    	}else{
    	    if (!isset($info['type']) || empty($info['type'])){
    	        $info['type'] = 0;
    	    }
    	    
    	    $start  =   0;
    	    $end    =   AC::RECOMMENT_USER_LIST_LEN;
    	    if (isset($info['start'])){
    	        if ($info['start']<0){
    	            $info['start'] = 0;
    	        }
    	        $start  =   $info['start'];
    	        $end    =   $info['start'] + $info['length'];
    	    }
    	    
    	    # model=>0随机模式，1为分页模式
    	    $model = 0;
    	    isset($info['model'])  && $model  = intval($info['model']);
    	    $type	=	intval($info['type']);
    	    
    	    # 获取用户列表
    	    $uids = $this->getUids($info['uid'],$type, 0, 0, -1, intval($info['length']));
    	    if ($model != 0){
    	        $uids = $this->getUids($info['uid'],$type, $model, $start, $end, intval($info['length']));
    	    }
    	}
    	if (empty($uids)) return (Object) array();
    	
    	// 组装返回数据
    	foreach($uids as $val){
    		$recuser = $this->rebuildData($val);
    		$recuser['is_followme']      = $this->autoUidModel->checkUserFans($info['uid'], $val);
    		$recuser['is_mefollow']      = $this->autoUidModel->checkUserFollow($info['uid'], $val);
    	    $result['userlist'][] 		= $recuser;	 
    	}
    	
    	$result['count_numbers']  		= count($result['userlist']);
    	
    	return $result;
    }/*}}}*/
    
    /**
     * 获取推荐用户接口
     * @param unknown $info
     * @return boolean|StdClass|number
     */
    public function getRecommentUsers ($info) {
        if (empty($info['uid'])) {
            AC::$errorNo    =   'FOC001';
            return  FALSE;
        }
         
        $uid    =   AC::HOST_UID;
        $rtype  =   0;
        $start  =   0;
        $length =   AC::RECOMMENT_USER_LIST_LEN;
        isset($info['rtype'])    &&    $rtype    =    intval($info['rtype']);
        isset($info['start'])    &&    $start    =    intval(floor(abs($info['start'])));
        isset($info['length'])   &&    $length   =    intval(floor(abs($info['length'])));
        
        if ($rtype > 0) {
            // 查询用户标签情况，根据标签搜索用户
            $userInfo = $this->autoUidModel->getUserInfo($uid);
            if (empty($userInfo['tag_list'])) {
                return (Object) array();
            }
            
            // 组装关键词
            $tags = array();
            foreach ($userInfo['tag_list'] as $value){
                $tags[] = $value['name'];
            }
            $tags_str = implode(',', $tags);
            
            // 请求返回
            $data = array('start' => $start, 'length' => $length, 'tags_str' => $tags_str);
            $uids = $this->hotSquareModel->getSearchUsersByTag($uid, $data);
        }else{
            // 获取redis中的用户
            $boardActiveUids = $this->diaryListCacheModel->getBoardUids();
            $recommendActiveUids = $this->diaryListCacheModel->getBoardUids('recommend');
            if (empty($boardActiveUids)) {
                $boardActiveUids = $this->defaultActiveUids();
            }

            $boardActiveUids = $this->hotSquareModel->filterSelfAndOfficials($uid, $boardActiveUids);
            $recommendActiveUids = $this->hotSquareModel->filterSelfAndOfficials($uid, $recommendActiveUids);
            $boardActiveUids=array_diff($boardActiveUids,$recommendActiveUids);
            $week = date("w", AC::SERVER_TIME);
            if (($week * $length) > 0) {
                $week_early_data = array_slice($boardActiveUids, 0, ($week * $length));
                $boardActiveUids = array_merge(array_diff($boardActiveUids, $week_early_data), $week_early_data);
            }
            if($start==0){
                $boardActiveUids =array_merge($recommendActiveUids,$boardActiveUids);
            }
            $uids = array_slice($boardActiveUids, $start, $length);
        }
        if (empty($uids)) return (Object) array();

        $users = array();
        foreach($uids as $val){
            $recuser = $this->rebuildData($val);
            $recuser['is_followme']      = $this->autoUidModel->checkUserFans($info['uid'], $val);
            $recuser['is_mefollow']      = $this->autoUidModel->checkUserFollow($info['uid'], $val);
            $users[] 		= $recuser;
        }
        
        $result = array(
            'users' => $users,
            'ousers'=> $this->getOfficialAccounts(),
            'counts'=> count($users)
        );

        return $result;
    }
    
    private function getOfficialAccounts() {
        $result  =    array();
        $uid     =    AC::HOST_UID;

        // 组装返回数据
        foreach(AC::$officialAccounts['recommend'] as $val){
            $recuser = $this->rebuildData($val);
            $recuser['is_followme']      = $this->autoUidModel->checkUserFans($uid, $val);
            $recuser['is_mefollow']      = $this->autoUidModel->checkUserFollow($uid, $val);
            $result[] 		= $recuser;
        }
        return $result;
    }
    
    #　返回数据
    public function rebuildData($uid)/*{{{*/
    {
    	$userInfo 	   				= $this->autoUidModel->getUserInfo($uid);
    	$recuser['uid']				= $uid;
    	$recuser['nickname']		= $this->autoUidModel->getRemarkName($userInfo);
    	$recuser['avatar']			= $userInfo['avatar'];
    	$recuser['signature']		= $userInfo['signature'];
    	$recuser['user']            = $this->autoUidModel->checkIsMe($userInfo);
    	$recuser['user']['nickname']= $recuser['nickname'];
    	return $recuser;
    }
    
    # 取列表，防空数据
    private function getUids($uid,$type,$model,$start,$end,$length)/*{{{*/
    {
    	$uids   =   $this->diaryListCacheModel->recommentUserList($type,$start,$end);
    	if ($type==0 && empty($uids))
    	{
    		$data['start']	=	$start;
    		$data['length']	=	$end;
    		$hotuids	    =	$this->gethotusers($data);
    		$hotuids['type']=	1;
    		$this->addRecommentUser($hotuids);
    		$uids   =   $this->diaryListCacheModel->recommentUserList($type,$start,$end);
    	}
    	
    	// 先过滤已关注的
    	$uids    =   $this->diaryListCacheModel->recommentUserList($type,0,-1);
    	$friends = 	 $this->diaryListCacheModel->getFriendsList($uid);
    	$friends[] = AC::HOST_UID;
    	$uids    =   array_diff($uids, $friends);
    	
    	// 判断官方账号是否关注、用于官方账号置顶
    	/*
	$ffrj_is_friend    =   $this->diaryListCacheModel->checkIsFriend($uid, '1');
	$ffrj_is_recomment =   $this->diaryListCacheModel->getUserScore('1');
        	
	// 随机取值
	if ($model == 0 && $ffrj_is_recomment && $ffrj_is_friend)
	{
		$uids = $this->array_random_assoc($uids,$length);
	}else{
		$ffji = array('1');
		$uids = $this->array_random_assoc($uids,$length-1);
		// $uids = array_merge($ffji,$uids);
	} 
    	*/
        $uids = UK::array_random_assoc($uids,$length);
    	return $uids;
    }
    
    # 从最热日记列表中取用户
    private function gethotusers($info)/*{{{*/
    {
    	$userlist 	= 	$this->hotSquareModel->getSquareLatestUserList($info);
    	$uids 		=	array();
    	foreach ($userlist as $value)
    	{
    		$uids[]	=	$value['uid'];
    	}
   		$result['uid']     =  implode(',',$uids);
    	return $result;
    }/*}}}*/

    # 获取用户最新发布日记的时间
    private function getLastestDiary($uid)/*{{{*/
    {
    	$result		 =	$this->diaryListModel->getLastestDiary($uid);
    	$lastestTime =  $result[0]['time'];
    	return $lastestTime;
    }
    
    private function defaultActiveUids () {
        $uids = array(6322853,6101403,6267270,6339713,5928982,6357293,6322316,4996576,5472567,5430731,5877605,4983036,
                5471741,6161742,5851633,4635177,6339416,6256102,5803580,5527281,6361081,6343170,6264372,6357369,6095981,
                6272875,6258901,5873692,5781927,6170425,5781721,6170639,6354172,5571891,6261395,5934000,6101381,6167272,
                5096459,5095824,5844339,6054281,3126804,6326955,5720935,5743494,3998952,5820239,6353020,6322805,4024208,
                6176896,6299599,5441338,5784241,6268899,5367244,5665049,6360761,5233211,5705505,4186475,6197331,3831914,
                6123971,6359401,6349023,6348426,5851480,6351402,5981483,6343726,5235380,6356938,3965060,4826315,6179133,
                6323174,5831178,4913698,6342785,5808555,5632960,6309276,6262039,6282082,4915803,6315711,5176562,5754892,
                5672057,5569782,5681518,6360620,5723928,6290085,5457642,5711207,6268612,5854819,3026634,5235892,5846151,
                3772059,3009134,6355843,5795329,3957689,6278555,5099177,5257631,5877827,5960186,5943946,6272833,6151108,
                6060099,6354171,5764995,6223466,3243388,6360709,5927747,6295943,5900455,6276389,5242125,5251069,
                5934086,6300136,6089489,4496841,6314911,5220510,6359353,3991911,4950879,6261917,6316448,6197211,6310452,
                4736344,5898066,5252577,6010399,4815002,3882964,6059218);
        
        return $uids;
    }
    
    private function getSquareDetail($info)/*{{{*/
    {
        if (empty($info['eUid']))   return  NULL;

        $info['uid']=   $info['eUid'];
        $modelInfo  =   $this->squareTypeModel($info['type']);
        if (empty($modelInfo['model'])) return  FALSE;

        $object =   $this->modelObject($modelInfo['model']);
        if (empty($object))
        {
            #   AC::$errorNo    =   'HSCC003';
            return  NULL;
        }

        $detail =   $object->$modelInfo['method']($info);
        if (!empty($detail['secret']))  return  NULL;

        if (empty($detail['attachmentPath']) || empty($detail['uid'])   ||  empty($detail['bodyId']))   return  $detail;
        // 语音附件
        $attachment   =   $this->diaryAttachmentModel->getDiaryAllAttachment($detail);
        $detail['attachmentList']    =    $attachment['attachmentList'];
        $detail['voiceList']         =    $attachment['voiceList'];
        return  $detail;
    }/*}}}*/

    private function squareTypeModel($type)/*{{{*/
    {
        $squareType     =   array(
                            AC::FEED_DIARY  =>  'DiaryListModel:getDiaryListInfo',
                        );
        if (empty($squareType[$type]))  return  NULL;

        list($info['model'], $info['method'])   =   explode(':', $squareType[$type]);
        return  $info;
    }/*}}}*/

    private function modelObject($model)/*{{{*/
    {
        if (isset(self::$modelPool[$model]))
        {
            return  self::$modelPool[$model];
        }

        self::$modelPool[$model]    =   new $model();
        return  self::$modelPool[$model];
    }/*}}}*/

}

